/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.j2eefast.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.j2eefast.web.entity.ClassifyEntity;
import com.j2eefast.web.mapper.ClassifyMapper;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.utils.Constant;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.List;
import java.util.Arrays;

/**
 * 【请填写功能名称】Service接口
 * @author: ZhouZhou
 * @date 2021-06-11 10:29:57
 */
@Service
public class ClassifyService extends ServiceImpl<ClassifyMapper,ClassifyEntity> {

	@Resource
	private ClassifyMapper classifyMapper;

	private final static String FORMAT_URL = "http://items.aiyangniu.cn/classifys/list/%s";

	public List<ClassifyEntity> getThreeClassify(){
		ClassifyEntity query = new ClassifyEntity();
		query.setLevel(3);

		return classifyMapper.findList(query);
	}

	public void initClassify() {

		String baseUrl = "http://items.aiyangniu.cn/classifys/list/0";

		JSONObject data = doRequest(baseUrl);
		JSONArray classifyArr = data.getJSONArray("data");
		for (int i = 0; i < classifyArr.size(); i++) {
			JSONObject o = JSONUtil.parseObj(classifyArr.get(i));
			ClassifyEntity classify = getData(o);
			saveData(classify);
			doParse(classify.getId());
		}


	}

	private void doParse(int id) {

		String url = String.format(FORMAT_URL, id);
		JSONObject data = doRequest(url);
		JSONArray array = data.getJSONArray("data");
		if (array == null || array.size() == 0) {
			return;
		}

		for (int i = 0; i < array.size(); i++) {
			JSONObject o = JSONUtil.parseObj(array.get(i));

			ClassifyEntity classify = getData(o);
			saveData(classify);
			doParse(classify.getId());

		}
	}

	private ClassifyEntity getData(JSONObject o) {
		ClassifyEntity data = new ClassifyEntity();
		data.setCoverImage(o.getStr("cover_image"));
		data.setId(o.getInt("id"));
		data.setName(o.getStr("name"));
		data.setParentId(o.getInt("parentId"));
		data.setSort(o.getInt("sort"));

		if (StrUtil.isBlankIfStr(data.getCoverImage())) {
			data.setCoverImage("");
		}

		return data;
	}

	private JSONObject doRequest(String url) {
		String result = HttpUtil.get(url);

		JSONObject data = JSONUtil.parseObj(result);

		return data;
	}

	private void saveData(ClassifyEntity classify) {
		ClassifyEntity query = new ClassifyEntity();
		query.setId(classify.getParentId());
		List<ClassifyEntity> parentData = classifyMapper.findList(query);
		if (parentData != null && parentData.size() >0) {
			classify.setLevel(parentData.get(0).getLevel()+ 1);
		} else {
			classify.setLevel(1);
		}

		ClassifyEntity exist = new ClassifyEntity();
		exist.setId(classify.getId());
		List<ClassifyEntity> dataList = classifyMapper.findList(exist);
		if(dataList != null && dataList.size() > 0){
			classify.setPkId(dataList.get(0).getPkId());
		}

		this.saveOrUpdate(classify);
	}

	/**
	 * mybaitis-plus 单表页面分页查询
     */
	public PageUtil findPage(Map<String, Object> params) {
		QueryWrapper<ClassifyEntity> queryWrapper = new QueryWrapper<ClassifyEntity>();
		String parentId = (String) params.get("parentId");
        queryWrapper.eq(ToolUtil.isNotEmpty(parentId), "parent_id", parentId);
		String coverImage = (String) params.get("coverImage");
        queryWrapper.eq(ToolUtil.isNotEmpty(coverImage), "cover_image", coverImage);
		String name = (String) params.get("name");
        queryWrapper.like(ToolUtil.isNotEmpty(name), "name", name);
		String sort = (String) params.get("sort");
        queryWrapper.eq(ToolUtil.isNotEmpty(sort), "sort", sort);
		String level = (String) params.get("level");
        queryWrapper.eq(ToolUtil.isNotEmpty(level), "level", level);
		Page<ClassifyEntity> page = classifyMapper.selectPage(new Query<ClassifyEntity>(params).getPage(), queryWrapper);
		return new PageUtil(page);
    }

	/**
	 * 自定义分页查询，含关联实体对像
	 */
	public PageUtil findPage(Map<String, Object> params,ClassifyEntity classifyEntity) {
		Page<ClassifyEntity> page = classifyMapper.findPage(new Query<ClassifyEntity>(params).getPage(),
					classifyEntity,
				(String) params.get(Constant.SQL_FILTER));
		return new PageUtil(page);
	}

	/**
	* 查列表
	*/
	public List<ClassifyEntity> findList(ClassifyEntity classifyEntity){
		return classifyMapper.findList(classifyEntity);
	}

	/**
     * 批量删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteBatchByIds(Integer[] ids) {
		return this.removeByIds(Arrays.asList(ids));
	}

	/**
     * 单个删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean delClassifyById(Integer pkId) {
		return this.removeById(pkId);
	}

	/**
     * 保存
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean addClassify(ClassifyEntity classify){
		if(this.save(classify)){
			return true;
		}
        return false;
    }

	/**
     * 修改根居ID
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateClassifyById(ClassifyEntity classify) {
		if(this.updateById(classify)){
			return true;
		}
		return false;
	}

	/**
     * 根居ID获取对象
     */
	public ClassifyEntity findClassifyById(Integer pkId){
		return classifyMapper.findClassifyById(pkId);
	}


}
